/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RolesViewExt.java
 *
 * Created on 2009-10-27, 13:28:05
 */
package com.openbravo.pos.admin;

import cn.ekuma.data.ui.swing.AbstractDAOJEditor;
import cn.ekuma.epos.businesslogic.AdminUtil;
import cn.ekuma.epos.businesslogic.RoleUtil;
import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.user.DirtyManager;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.bean.Role;
import com.openbravo.bean.erp.OrderType;
import com.openbravo.bean.shard.UserOrderTypePermission;
import com.openbravo.bean.shard.UserPermission;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import javax.swing.AbstractListModel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.jdesktop.swingx.treetable.AbstractTreeTableModel;
import org.jdesktop.swingx.treetable.TreeTableNode;
import org.jgraph.JGraph;
import org.jgraph.graph.DefaultGraphModel;
import org.ofsm.creator.StateDiagramManager;
import org.ofsm.impl.FileFiniteStateMachineModel;
import javax.swing.JPanel;
import java.awt.BorderLayout;


/**
 *
 * @author Administrator
 */
public class RolesViewExt extends AbstractDAOJEditor<Role> {

    List<PermissionTreeTableNode> permissionList;
    DirtyManager m_dirty;
    TreeTableNode root;
    PermissionTreeTableModel tableModel;
    Map<String,FileFiniteStateMachineModel> stateMachineModels;
    Object[] stateArray;
    List<OrderType> orderTypes;
    GrantEventTableModel grantEventTableModel;
    GrantEventTableModel grantEventTableModel1;
    Map<String,UserOrderTypePermission> roleOrderTypePermissions;
    Map<String,UserOrderTypePermission> roleStateProcessPermissions;
    String curOrderTypeId;
    private StateDiagramManager stateDiagramMgr;
	private JScrollPane jScrollPane41;
	private JTable jEventGrantTable1;
	private JScrollPane jScrollPane51;
	private JGraph diagramGraph1;
	private JScrollPane jScrollPane11;
	private JList jOrderTypeList1;
	private JPanel jPanel41;
	private String curStateSelected;
	List<UserPermission> m_apermissions;


    /** Creates new form RolesViewExt */
    public RolesViewExt(DirtyManager dirty, I_DataLogicSystem m_dlSystem,I_DataLogicERP dlSales) {
    	super(dirty);
        initComponents();
        m_jName.getDocument().addDocumentListener(dirty);
        jadvCode.getDocument().addDocumentListener(dirty);
        m_jText.getDocument().addDocumentListener(dirty);
        m_apermissions = RoleUtil.fillPermissions(m_dlSystem, "0");//admin的权限当作模版
        permissionList = new ArrayList<PermissionTreeTableNode>();
        root = buildPermissionRootNode(m_apermissions);
        tableModel = new PermissionTreeTableModel(root);
        jRolePermissionTable.setRootVisible(false);
        jRolePermissionTable.setTreeTableModel(tableModel);
        m_dirty = dirty;
        try {
            stateMachineModels=AdminUtil.getALLStateMachines(m_dlSystem);
            orderTypes = dlSales.list(OrderType.class);
        } catch (BasicException ex) {
            new MessageInf(ex).show(this);
            orderTypes=new ArrayList();
        }
        jOrderTypeList.setModel(new AbstractListModel(){
            public int getSize() {
                return orderTypes.size();
            }
            public Object getElementAt(int index) {
               return orderTypes.get(index);
            }
        });
        grantEventTableModel=new GrantEventTableModel();
        
        jEventGrantTable.setModel(grantEventTableModel);
        
        stateArray= stateMachineModels.keySet().toArray();
        
        jOrderTypeList1.setModel(new AbstractListModel(){
            public int getSize() {
                return stateArray.length;
            }
            
            public Object getElementAt(int index) {
               return stateArray[index];
            }
        });
        
        grantEventTableModel1=new GrantEventTableModel();
        jEventGrantTable1.setModel(grantEventTableModel1);
    }

    /**

    public void writeValueEOF() {
        m_oId = null;
        m_jName.setText(null);
        jadvCode.setText(null);
        m_jText.setText(null);
        m_jName.setEnabled(false);
        jRolePermissionTable.setEnabled(false);
        jadvCode.setEnabled(false);
        m_jText.setEnabled(false);
        curOrderTypeId=null;
        curStateSelected=null;
        selectedNull();
        roleOrderTypePermissions=new HashMap();
        grantEventTableModel.init(null, null);
        jOrderTypeList.clearSelection();
        diagramGraph.setModel(new DefaultGraphModel());
        
        roleStateProcessPermissions=new HashMap();
        grantEventTableModel1.init(null, null);
        jOrderTypeList1.clearSelection();
        diagramGraph1.setModel(new DefaultGraphModel());
    }

    public void writeValueInsert(Properties prop) {
        m_oId = null;
        m_jName.setText(null);
        jadvCode.setText(null);
        m_jText.setText(null);
        m_jName.setEnabled(true);
        jadvCode.setEnabled(true);
        jRolePermissionTable.setEnabled(true);
        m_jText.setEnabled(true);
        curOrderTypeId=null;
        curStateSelected=null;
        selectedNull();
        roleOrderTypePermissions=new HashMap();
        grantEventTableModel.init(null, null);
        jOrderTypeList.clearSelection();
        diagramGraph.setModel(new DefaultGraphModel());
        
        
        roleStateProcessPermissions=new HashMap();
        grantEventTableModel1.init(null, null);
        jOrderTypeList1.clearSelection();
        diagramGraph1.setModel(new DefaultGraphModel());
    }

    public void writeValueDelete(Object value) {
        Object[] role = (Object[]) value;
        m_oId = role[0];
        m_jName.setText(Formats.STRING.formatValue(role[1]));
        String sRolePermisions = Formats.BYTEA.formatValue(role[2]);
        m_jText.setText(sRolePermisions);
        jadvCode.setText(Formats.STRING.formatValue(role[3]));
        checkPermissions(sRolePermisions);
        m_jName.setEnabled(false);
        jadvCode.setEnabled(false);
        jRolePermissionTable.setEnabled(false);
        m_jText.setEnabled(false);
        curOrderTypeId=null;
        curStateSelected=null;
        String sRoleOrderTypePermisions = Formats.BYTEA.formatValue(role[4]);
        checkOrderTypePermissions(sRoleOrderTypePermisions);
        grantEventTableModel.init(null, null);
        diagramGraph.setModel(new DefaultGraphModel());
        jOrderTypeList.clearSelection();
        
        roleStateProcessPermissions=new HashMap();
        grantEventTableModel1.init(null, null);
        jOrderTypeList1.clearSelection();
        diagramGraph1.setModel(new DefaultGraphModel());
    }

    public void writeValueEdit(Object value) {
        Object[] role = (Object[]) value;
        m_oId = role[0];
        m_jName.setText(Formats.STRING.formatValue(role[1]));
        String sRolePermisions = Formats.BYTEA.formatValue(role[2]);
        m_jText.setText(sRolePermisions);
        jadvCode.setText(Formats.STRING.formatValue(role[3]));
        checkPermissions(sRolePermisions);
        m_jName.setEnabled(true);
        jadvCode.setEnabled(true);
        if ("0".equalsIgnoreCase((String) m_oId)) {//admin
            jRolePermissionTable.setEnabled(false);
            m_jText.setEnabled(true);
        } else {
            jRolePermissionTable.setEnabled(true);
            m_jText.setEnabled(false);
        }
        curOrderTypeId=null;
        curStateSelected=null;
        String sRoleOrderTypePermisions=null;
        if(role[4]!=null)
            sRoleOrderTypePermisions = Formats.BYTEA.formatValue(role[4]);
        checkOrderTypePermissions(sRoleOrderTypePermisions);
        grantEventTableModel.init(null, null);
        diagramGraph.setModel(new DefaultGraphModel());
        jOrderTypeList.clearSelection();
        
        String sroleStateProcessPermissions=null;
        if(role[5]!=null)
            sroleStateProcessPermissions = Formats.BYTEA.formatValue(role[5]);
        checkRoleStateProcessPermissions(sroleStateProcessPermissions);
        
        grantEventTableModel1.init(null, null);
        jOrderTypeList1.clearSelection();
        diagramGraph1.setModel(new DefaultGraphModel());
    }

    public Object createValue() throws BasicException {
        Object[] role = new Object[6];
        role[0] = m_oId == null ? UUID.randomUUID().toString() : m_oId;
        role[1] = m_jName.getText();
        if (jTabbedPane1.getSelectedIndex() == 0 || !"0".equalsIgnoreCase((String) m_oId)) {
            role[2] = Formats.BYTEA.parseValue(buildXmlForSelectedPermissions());
        } else {
            role[2] = Formats.BYTEA.parseValue(m_jText.getText());
        }
        String advCode = jadvCode.getText();
        role[3] = advCode == null ? UUID.randomUUID().toString() : advCode;
        role[4]=Formats.BYTEA.parseValue(RoleUtil.buildOrderTypePermissionXml(roleOrderTypePermissions.values()));
        role[5]=Formats.BYTEA.parseValue(RoleUtil.buildOrderTypePermissionXml(roleStateProcessPermissions.values()));
        return role;
    }
    
    */

    private void checkPermissions(String sRolePermisions) {
        selectedNull();
        List<UserPermission> rolePermissions = RoleUtil.formatPermissions(sRolePermisions);
        for (UserPermission permission : rolePermissions) {
            for (PermissionTreeTableNode node : permissionList) {
                if (node.getPermission().equals(permission)) {
                    node.setSelected(true);
                }
            }
        }
        tableModel.reflush();
        jRolePermissionTable.expandAll();
    }


    private void checkOrderTypePermissions(String sRoleOrderTypePermisions) {
        this.roleOrderTypePermissions = RoleUtil.formatOrderTypePermissions(sRoleOrderTypePermisions);
    }

    private void checkRoleStateProcessPermissions(String sroleStateProcessPermissions) {
        this.roleStateProcessPermissions = RoleUtil.formatOrderTypePermissions(sroleStateProcessPermissions);
    }
    
    
    public Component getComponent() {
        return this;
    }

    @Override
    public void refresh() {
    }

    private String buildXmlForSelectedPermissions() {
        List<UserPermission> selectedPermissions=new ArrayList<UserPermission>();
        for(PermissionTreeTableNode node:this.permissionList){
        if(node.isSelected())
            selectedPermissions.add(node.getPermission());
        }
        return RoleUtil.buildXml(selectedPermissions);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        m_jName = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jadvCode = new javax.swing.JTextField();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jRolePermissionTable = new org.jdesktop.swingx.JXTreeTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        m_jText = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jEventGrantTable = new javax.swing.JTable();
        jScrollPane5 = new javax.swing.JScrollPane();
        diagramGraph = new org.jgraph.JGraph();
        jScrollPane1 = new javax.swing.JScrollPane();
        jOrderTypeList = new javax.swing.JList();

        jPanel41 = new javax.swing.JPanel();
        jScrollPane41 = new javax.swing.JScrollPane();
        jEventGrantTable1 = new javax.swing.JTable();
        jScrollPane51 = new javax.swing.JScrollPane();
        diagramGraph1 = new org.jgraph.JGraph();
        jScrollPane11 = new javax.swing.JScrollPane();
        jOrderTypeList1 = new javax.swing.JList();
        
        setLayout(new java.awt.BorderLayout());

        jLabel2.setText(AppLocal.getIntString("Label.Name")); // NOI18N

        jLabel1.setText(AppLocal.getIntString("label.RolePermissionCode")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(m_jName, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jadvCode, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(69, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(m_jName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)
                        .addComponent(jadvCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(jPanel1, java.awt.BorderLayout.NORTH);

        jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);

        jScrollPane3.setViewportView(jRolePermissionTable);

        jTabbedPane1.addTab(AppLocal.getIntString("label.basePermission"), jScrollPane3); // NOI18N

        jPanel2.setLayout(new java.awt.BorderLayout());

        m_jText.setFont(new java.awt.Font("DialogInput", 0, 12));
        jScrollPane2.setViewportView(m_jText);

        jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("txt", jPanel2);

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel4.setLayout(new java.awt.BorderLayout());

        jScrollPane4.setPreferredSize(new java.awt.Dimension(80, 200));

        jEventGrantTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jEventGrantTable.setPreferredSize(new java.awt.Dimension(80, 200));
        jScrollPane4.setViewportView(jEventGrantTable);

        jPanel4.add(jScrollPane4, java.awt.BorderLayout.PAGE_START);

        jScrollPane5.setViewportView(diagramGraph);

        jPanel4.add(jScrollPane5, java.awt.BorderLayout.CENTER);

        jPanel3.add(jPanel4, java.awt.BorderLayout.CENTER);

        jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 0));

        jOrderTypeList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jOrderTypeList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jOrderTypeListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jOrderTypeList);

        jPanel3.add(jScrollPane1, java.awt.BorderLayout.WEST);

        jTabbedPane1.addTab(AppLocal.getIntString("label.OrderTypePermission"), jPanel3); // NOI18N

       
        
        panel = new JPanel();
        
        panel.setLayout(new BorderLayout());
        
        jPanel41.setLayout(new java.awt.BorderLayout());

        jScrollPane41.setPreferredSize(new java.awt.Dimension(80, 200));

        jEventGrantTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jEventGrantTable1.setPreferredSize(new java.awt.Dimension(80, 200));
        jScrollPane41.setViewportView(jEventGrantTable1);

        jPanel41.add(jScrollPane41, java.awt.BorderLayout.PAGE_START);

        jScrollPane51.setViewportView(diagramGraph1);

        jPanel41.add(jScrollPane51, java.awt.BorderLayout.CENTER);

        panel.add(jPanel41, java.awt.BorderLayout.CENTER);

        jScrollPane11.setPreferredSize(new java.awt.Dimension(250, 0));

        jOrderTypeList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jOrderTypeList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jOrderTypeListValueChanged1(evt);
            }
        });
        jScrollPane11.setViewportView(jOrderTypeList1);

        panel.add(jScrollPane11, java.awt.BorderLayout.WEST);
        jTabbedPane1.addTab("状态转换权限", null, panel, null);
        
        add(jTabbedPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void jOrderTypeListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jOrderTypeListValueChanged
          OrderType selected= (OrderType)jOrderTypeList.getSelectedValue();
          if(selected!=null){
              if(curOrderTypeId!=null){
                 List<String> beforeList=grantEventTableModel.getGrantEvents();
                 UserOrderTypePermission beforeOrderTypePermission=this.roleOrderTypePermissions.get(curOrderTypeId);
                 beforeOrderTypePermission.setGrantEvents(beforeList);
              }
              String orderStateMachineName=selected.getStateMachine();
              String orderTypeId=selected.getId();
              curOrderTypeId=orderTypeId;
              FileFiniteStateMachineModel orderTypeStateMachineModel=stateMachineModels.get(orderStateMachineName);
              List<String> orderTypeEvents=orderTypeStateMachineModel.getEventNames();
              orderTypeEvents.add(AppLocal.getIntString(UserOrderTypePermission.ORDERTYPEEVENT_Create));
              orderTypeEvents.add(AppLocal.getIntString(UserOrderTypePermission.ORDERTYPEEVENT_Delete));
              orderTypeEvents.add(AppLocal.getIntString(UserOrderTypePermission.ORDERTYPEEVENT_Edit));
              UserOrderTypePermission orderTypePermission=this.roleOrderTypePermissions.get(orderTypeId);
              if(orderTypePermission==null){
                       orderTypePermission=new UserOrderTypePermission(orderTypeId);
                       roleOrderTypePermissions.put(orderTypeId, orderTypePermission);
              }
              List<String> grantEvents=orderTypePermission.getGrantEvents();
              grantEventTableModel.init(orderTypeEvents, grantEvents);
              stateDiagramMgr = new StateDiagramManager(orderTypeStateMachineModel, diagramGraph);
              stateDiagramMgr.setupModel();
              diagramGraph.updateUI();
          }
    }//GEN-LAST:event_jOrderTypeListValueChanged

    private void jOrderTypeListValueChanged1(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jOrderTypeListValueChanged
        String selected= (String)jOrderTypeList1.getSelectedValue();
        if(selected!=null){
            if(curStateSelected!=null){
               List<String> beforeList=grantEventTableModel1.getGrantEvents();
               UserOrderTypePermission beforeStatePermission=this.roleStateProcessPermissions.get(curStateSelected);
               beforeStatePermission.setGrantEvents(beforeList);
            }
            curStateSelected=selected;
            FileFiniteStateMachineModel stateProcessStateMachineModel=stateMachineModels.get(selected);
            List<String> processEvents=stateProcessStateMachineModel.getEventNames();
            UserOrderTypePermission userStateProcessPermission=this.roleStateProcessPermissions.get(selected);
            if(userStateProcessPermission==null){
            	userStateProcessPermission=new UserOrderTypePermission(selected);
                     roleStateProcessPermissions.put(selected, userStateProcessPermission);
            }
            List<String> grantEvents=userStateProcessPermission.getGrantEvents();
            grantEventTableModel1.init(processEvents, grantEvents);
            stateDiagramMgr = new StateDiagramManager(stateProcessStateMachineModel, diagramGraph1);
            stateDiagramMgr.setupModel();
            diagramGraph1.updateUI();
        }   
  }//GEN-LAST:event_jOrderTypeListValueChanged
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jgraph.JGraph diagramGraph;
    private javax.swing.JTable jEventGrantTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jOrderTypeList;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private org.jdesktop.swingx.JXTreeTable jRolePermissionTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField jadvCode;
    private javax.swing.JTextField m_jName;
    private javax.swing.JTextArea m_jText;
    private JPanel panel;
    // End of variables declaration//GEN-END:variables

    private void selectedNull() {
        for (PermissionTreeTableNode node : permissionList) {
            node.setSelected(false);
        }
    }
    // End of variables declaration

    private String getLocalPermissionName(String permission) {
        if (permission.startsWith("/")) {
            permission = permission.substring(1);
        }
        permission = permission.replaceAll("/", ".");
        return AppLocal.getIntString("role." + permission);
    }

    private TreeTableNode buildPermissionRootNode(List<UserPermission> userPermission) {
        PermissionGroupTreeTableNode temp = new PermissionGroupTreeTableNode(null, "root");
        PermissionGroupTreeTableNode groupTemp = null;
        PermissionTreeTableNode premissionTemp = null;
        for (UserPermission permission : userPermission) {
            String groupName = permission.getGroup();
            if (groupName == null) {
                groupName = UserPermission.PERMISSIONGROUP_Default;
            }
            groupName=getLocalPermissionName("group."+groupName);
            groupTemp = findPermissionGroupByName(temp.getChildren(), groupName);
            if (groupTemp == null) {
                groupTemp = new PermissionGroupTreeTableNode(temp, groupName);
                temp.add(groupTemp);
            }
            premissionTemp = new PermissionTreeTableNode(groupTemp, permission, getLocalPermissionName(permission.getPermission()));
            groupTemp.add(premissionTemp);
            permissionList.add(premissionTemp);
        }
        return temp;
    }

    private PermissionGroupTreeTableNode findPermissionGroupByName(List<TreeTableNode> nodes, String groupName) {
        for (TreeTableNode node : nodes) {
            if ((node instanceof PermissionGroupTreeTableNode) && ((PermissionGroupTreeTableNode) node).getGroupName().equalsIgnoreCase(groupName)) {
                return (PermissionGroupTreeTableNode) node;
            }
        }
        return null;
    }

    class PermissionTreeTableModel extends AbstractTreeTableModel {

        public PermissionTreeTableModel(TreeTableNode root) {
            super(root);
        }

        @Override
        public Class<?> getColumnClass(int column) {
            if (column == 1) {
                return Boolean.class;
            }
            return super.getColumnClass(column);
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public Object getValueAt(Object node, int column) {
            if (column < 0 || column >= getColumnCount()) {
                throw new IllegalArgumentException("column must be a valid index");
            }

            TreeTableNode ttn = (TreeTableNode) node;

            if (column >= ttn.getColumnCount()) {
                return null;
            }

            return ttn.getValueAt(column);
        }

        @Override
        public Object getChild(Object parent, int index) {
            return ((TreeTableNode) parent).getChildAt(index);
        }

        @Override
        public int getChildCount(Object parent) {
            return ((TreeTableNode) parent).getChildCount();
        }

        @Override
        public int getIndexOfChild(Object parent, Object child) {
            return ((TreeTableNode) parent).getIndex((TreeTableNode) child);
        }

        public void reflush() {
            modelSupport.fireNewRoot();
        }

        @Override
        public void setValueAt(Object value, Object node, int column) {

            if (column < 0 || column >= getColumnCount()) {
                throw new IllegalArgumentException("column must be a valid index");
            }

            TreeTableNode ttn = (TreeTableNode) node;

            if (column < ttn.getColumnCount()) {
                ttn.setValueAt(value, column);

                modelSupport.fireTreeStructureChanged(new TreePath(getPathToRoot(ttn)));
            }
        }

        @Override
        public boolean isCellEditable(Object node, int column) {
            if (column < 0 || column >= getColumnCount()) {
                throw new IllegalArgumentException("column must be a valid index");
            }

            TreeTableNode ttn = (TreeTableNode) node;

            if (column >= ttn.getColumnCount()) {
                return false;
            }

            return ttn.isEditable(column);
        }

        public TreeTableNode[] getPathToRoot(TreeTableNode aNode) {
            List<TreeTableNode> path = new ArrayList<TreeTableNode>();
            TreeTableNode node = aNode;

            while (node != root) {
                path.add(0, node);

                node = (TreeTableNode) node.getParent();
            }

            if (node == root) {
                path.add(0, node);
            }

            return path.toArray(new TreeTableNode[0]);
        }
    }

    class PermissionTreeTableNode implements TreeTableNode {

        TreeTableNode parent;
        String permissionName;
        UserPermission permission;
        boolean selected;

        public PermissionTreeTableNode(TreeTableNode parent, UserPermission permission, String permissionName) {
            this.parent = parent;
            this.permission = permission;
            this.permissionName = permissionName;
            selected = false;
        }

        @Override
        public Enumeration<? extends TreeTableNode> children() {
            return null;
        }

        @Override
        public Object getValueAt(int i) {
            switch (i) {
                case 0:
                    return permissionName;
                case 1:
                    return selected;
            }
            return null;
        }

        @Override
        public TreeTableNode getChildAt(int i) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public TreeTableNode getParent() {
            return this.parent;
        }

        @Override
        public boolean isEditable(int i) {
            switch (i) {
                case 0:
                    return false;
                case 1:
                    return true;
            }
            return false;
        }

        @Override
        public void setValueAt(Object o, int i) {
            switch (i) {
                case 0:
                    return;
                case 1:
                    selected = (Boolean) o;
                    m_dirty.setDirty(true);
            }
        }

        @Override
        public Object getUserObject() {
            return permission;
        }

        @Override
        public void setUserObject(Object o) {
        }

        @Override
        public int getChildCount() {
            return 0;
        }

        @Override
        public int getIndex(TreeNode node) {
            return 0;
        }

        @Override
        public boolean getAllowsChildren() {
            return false;
        }

        @Override
        public boolean isLeaf() {
            return true;
        }

        public UserPermission getPermission() {
            return permission;
        }

        public boolean isSelected() {
            return selected;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof PermissionTreeTableNode) {
                PermissionTreeTableNode temp = (PermissionTreeTableNode) obj;
                return this.permission.equals(temp.getPermission());
            } else if (obj instanceof UserPermission) {
                UserPermission temp = (UserPermission) obj;
                return this.permission.equals(temp);
            }
            return false;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }

        @Override
        public String toString() {
            return this.permissionName;
        }
    }

    class PermissionGroupTreeTableNode implements TreeTableNode {

        TreeTableNode parent;
        List<TreeTableNode> children;
        String groupName;
        boolean selected;

        public PermissionGroupTreeTableNode(TreeTableNode parent, String groupName) {
            this.parent = parent;
            this.groupName = groupName;
            children = new ArrayList<TreeTableNode>();
            selected = false;
        }

        public void add(UserPermission permission) {
            children.add(new PermissionTreeTableNode(this, permission, getLocalPermissionName(permission.getPermission())));
        }

        public void add(TreeTableNode childNode) {
            children.add(childNode);
        }

        @Override
        public Enumeration<? extends TreeTableNode> children() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public Object getValueAt(int i) {
            switch (i) {
                case 0:
                    return groupName;
                case 1:
                    return selected;
            }
            return null;
        }

        @Override
        public TreeTableNode getChildAt(int i) {
            return children.get(i);
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public TreeTableNode getParent() {
            return parent;
        }

        @Override
        public boolean isEditable(int i) {
            switch (i) {
                case 0:
                    return false;
                case 1:
                    return true;
            }
            return false;
        }

        @Override
        public void setValueAt(Object o, int i) {
            if (i == 1) {
                selected = (Boolean) o;
                for (TreeTableNode childNode : children) {
                    childNode.setValueAt(selected, i);
                }
            }
        }

        @Override
        public Object getUserObject() {
            return children;
        }

        @Override
        public void setUserObject(Object o) {
        }

        @Override
        public int getChildCount() {
            return children.size();
        }

        @Override
        public int getIndex(TreeNode node) {
            return children.indexOf(node);
        }

        @Override
        public boolean getAllowsChildren() {
            return !children.isEmpty();
        }

        @Override
        public boolean isLeaf() {
            return false;
        }

        public String getGroupName() {
            return groupName;
        }

        public List<TreeTableNode> getChildren() {
            return children;
        }
    }

    class GrantEventTableModel extends AbstractTableModel{
        List<String> orderTypeEvents,grantEvents;

        public GrantEventTableModel() {
        }

        public void init(List<String> orderTypeEvents, List<String> grantEvents) {
            this.orderTypeEvents = orderTypeEvents;
            this.grantEvents = grantEvents;
            if(orderTypeEvents==null)
                this.orderTypeEvents=new ArrayList();
            if(grantEvents==null)
                this.grantEvents=new ArrayList();
            this.fireTableDataChanged();
        }

        public int getRowCount() {
        	if(orderTypeEvents==null)
        		return 0;
            return orderTypeEvents.size();
        }

        public int getColumnCount() {
            return 2;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            switch(columnIndex){
                case 0:
                    return orderTypeEvents.get(rowIndex);
                case 1:
                    return grantEvents.contains(orderTypeEvents.get(rowIndex));
            }
            return null;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            if(columnIndex==1){
                boolean selected=(Boolean)aValue;
                if(selected)
                    grantEvents.add(orderTypeEvents.get(rowIndex));
                else
                    grantEvents.remove(orderTypeEvents.get(rowIndex));
                m_dirty.setDirty(true);
            }
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if(columnIndex==1)
                return Boolean.class;
            return super.getColumnClass(columnIndex);
        }

        @Override
        public String getColumnName(int column) {
            return super.getColumnName(column);
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
             if(columnIndex==1)
                return true;
            return super.isCellEditable(rowIndex, columnIndex);
        }

        public List<String> getGrantEvents() {
            return grantEvents;
        }
    }

	@Override
	public void activate() throws BasicException {
		// TODO Auto-generated method stub
	}

	@Override
	public String getLogerString() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isLogAble() {
		// TODO Auto-generated method stub
		return false;
	}



	@Override
	public Role createNew(Properties prop) {
		return new Role();
	}



	@Override
	public void rebuild(Role obj) throws BasicException {
		    obj.setName(m_jName.getText());
	        if (jTabbedPane1.getSelectedIndex() == 0 || !"0".equalsIgnoreCase(obj.getID()==null?" ":obj.getID())) {
	        	List<UserPermission> selectedPermissions=new ArrayList<UserPermission>();
	            for(PermissionTreeTableNode node:this.permissionList){
	            if(node.isSelected())
	                selectedPermissions.add(node.getPermission());
	            }
	            obj.setPermissions(selectedPermissions);
	        } else {
	           m_apermissions=RoleUtil.formatPermissions(m_jText.getText());
	           obj.setPermissions(m_apermissions);
	        }
	        String advCode = jadvCode.getText();
	        obj.setM_advCode(advCode == null ? UUID.randomUUID().toString() : advCode);
	        obj.setOrderTypePermissions(roleOrderTypePermissions);
	        obj.setStateProcessPermissions(roleStateProcessPermissions);
	}



	@Override
	public void updateUI(boolean editAble, int state) {
		
        m_jName.setText(obj.getName());
        String sRolePermisions = RoleUtil.buildXml(obj.getPermissions());
        m_jText.setText(sRolePermisions);
        jadvCode.setText(obj.getM_advCode());
        checkPermissions(sRolePermisions);
        m_jName.setEnabled(true);
        jadvCode.setEnabled(true);
        if ("0".equalsIgnoreCase(obj.getID()==null?" ":obj.getID())) {//admin
            jRolePermissionTable.setEnabled(false);
            m_jText.setEnabled(true);
        } else {
            jRolePermissionTable.setEnabled(true);
            m_jText.setEnabled(false);
        }
        curOrderTypeId=null;
        curStateSelected=null;
        
        roleOrderTypePermissions = obj.getOrderTypePermissions();
       
        grantEventTableModel.init(null, null);
        diagramGraph.setModel(new DefaultGraphModel());
        jOrderTypeList.clearSelection();
        
        roleStateProcessPermissions=obj.getStateProcessPermissions();
        
        grantEventTableModel1.init(null, null);
        jOrderTypeList1.clearSelection();
        diagramGraph1.setModel(new DefaultGraphModel());
	}

	@Override
	public Class getEditClass() {
		return Role.class;
	}
}
